package com.buanalintas.sandals.pos.saledetail;

import com.buanalintas.bynga.Action;
import com.buanalintas.bynga.Controller;
import com.buanalintas.bynga.Dictionary;
import com.buanalintas.bynga.Field;
import com.buanalintas.bynga.Logger;
import com.buanalintas.bynga.Page;
import com.buanalintas.bynga.Persistence;
import com.buanalintas.bynga.Template;
import com.buanalintas.bynga.Utility;
import com.buanalintas.bynga.formatter.MoneyFormatter;
import com.buanalintas.bynga.generator.PageTransactionDetailList;
import com.buanalintas.sandals.pos.entities.PosMasterItem;
import com.buanalintas.sandals.pos.entities.PosMasterItemStock;
import com.buanalintas.sandals.pos.entities.PosMasterSize;
import com.buanalintas.sandals.pos.entities.PosMasterStatus;
import com.buanalintas.sandals.pos.entities.PosTransactionSaleDetail;
import com.buanalintas.sandals.pos.item.Item;
import com.buanalintas.sandals.pos.saledetail.AddSize;
import com.buanalintas.sandals.pos.status.Status;
import java.math.BigDecimal;
import java.util.List;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpSession;

public class SaleDetail extends Page {

    private Field saleDetailId;
    private Field saleDetailSaleId;
    private Field saleDetailItemId;
    private Field saleDetailSizeId;
    private Field saleDetailSize;
    private Field saleDetailQuantity;
    private Field saleDetailPrice;
    private Field saleDetailDiscountPercent;
    private Field saleDetailDiscountNominal;
    private Field saleDetailTotal;
    private  boolean ada = true;

    public SaleDetail() {
        super();
        setTheClass(PosTransactionSaleDetail.class);

        saleDetailId = new Field();
        saleDetailId.setName("saleDetailId");
        saleDetailId.setCaption("id");
        saleDetailId.setListProperties("");
        saleDetailId.setInputProperties("");
        getFields().add(saleDetailId);

        saleDetailSaleId = new Field();
        saleDetailSaleId.setName("saleDetailSaleId");
        saleDetailSaleId.setCaption("sale id");
        saleDetailSaleId.setListProperties("");
        saleDetailSaleId.setInputProperties("");
        getFields().add(saleDetailSaleId);

        saleDetailItemId = new Field();
        saleDetailItemId.setName("saleDetailItemId");
        saleDetailItemId.setCaption("item");
        saleDetailItemId.setListProperties("");
        saleDetailItemId.setInputProperties(" size=\"30\"");
        saleDetailItemId.getSelectorAction().add(new String[]{"value", "saleDetailPrice", "itemPriceShop"});
        saleDetailItemId.getSelectorColumns().add(new String[]{"itemCode", " Code", "width=\"5%\" nowrap"});
        saleDetailItemId.getSelectorColumns().add(new String[]{"itemModel", " Model", "width=\"90%\""});
        saleDetailItemId.setSelectorOrder("t.itemCode");
        saleDetailItemId.setRequired(true);
        getFields().add(saleDetailItemId);

        saleDetailSize = new Field();
        saleDetailSize.setName("saleDetailSize");
        saleDetailSize.setCaption("size");
        saleDetailSize.setListProperties(" align=\"left\" width=\"30%\" nowrap");
        saleDetailSize.setEntityRelation(PosMasterSize.class);
        saleDetailSize.setInputType(Field.INPUT_CHECK_BOX);
        saleDetailSize.setRequired(true);
        getFields().add(saleDetailSize);

        saleDetailSizeId = new Field();
        saleDetailSizeId.setName("saleDetailSizeId");
        saleDetailSizeId.setCaption("size");
        saleDetailSizeId.setListProperties(" align=\"left\" width=\"30%\" nowrap");
        saleDetailSizeId.setEntityRelation(PosMasterSize.class);
        saleDetailSizeId.setRequired(true);
        getFields().add(saleDetailSizeId);

        saleDetailQuantity = new Field();
        saleDetailQuantity.setName("saleDetailQuantity");
        saleDetailQuantity.setCaption("quantity");
        saleDetailQuantity.setListProperties(" align=\"right\" width=\"5%\" nowrap");
        saleDetailQuantity.setInputProperties(" size=\"3\"");
        saleDetailQuantity.setRequired(true);
        getFields().add(saleDetailQuantity);

        saleDetailPrice = new Field();
        saleDetailPrice.setName("saleDetailPrice");
        saleDetailPrice.setCaption("price");
        saleDetailPrice.setListProperties(" align=\"right\" width=\"10%\" nowrap");
        saleDetailPrice.setInputProperties(" size=\"8\"");
        saleDetailPrice.setRequired(true);
        saleDetailPrice.setFormater(MoneyFormatter.getInstance());
        getFields().add(saleDetailPrice);

        saleDetailDiscountPercent = new Field();
        saleDetailDiscountPercent.setName("saleDetailDiscountPercent");
        saleDetailDiscountPercent.setCaption("discount percent");
        saleDetailDiscountPercent.setListProperties(" align=\"right\" width=\"10%\" nowrap");
        saleDetailDiscountPercent.setInputProperties(" size=\"8\"");
        getFields().add(saleDetailDiscountPercent);

        saleDetailDiscountNominal = new Field();
        saleDetailDiscountNominal.setName("saleDetailDiscountNominal");
        saleDetailDiscountNominal.setCaption("discount nominal");
        saleDetailDiscountNominal.setListProperties(" align=\"right\" width=\"10%\" nowrap");
        saleDetailDiscountNominal.setInputProperties(" size=\"8\"");
        saleDetailDiscountNominal.setFormater(MoneyFormatter.getInstance());
        getFields().add(saleDetailDiscountNominal);

        saleDetailTotal = new Field();
        saleDetailTotal.setName("saleDetailTotal");
        saleDetailTotal.setCaption("total");
        saleDetailTotal.setListProperties(" align=\"right\" width=\"10%\" nowrap");
        saleDetailTotal.setInputProperties(" size=\"8\"");
        saleDetailTotal.setFormater(MoneyFormatter.getInstance());
        getFields().add(saleDetailTotal);

        getActions().add(Action.TRANS_DETAIL_LIST);
        getActions().add(Action.TRANS_DETAIL_ADD);
        getActions().add(Action.TRANS_DETAIL_EDIT);

        getFieldsAdd().clear();
        getFieldsAdd().add(saleDetailItemId);
        getFieldsAdd().add(saleDetailSize);
        getFieldsAdd().add(saleDetailQuantity);
        getFieldsAdd().add(saleDetailPrice);
        getFieldsAdd().add(saleDetailDiscountPercent);
        getFieldsAdd().add(saleDetailDiscountNominal);

        getFieldsEdit().clear();
        getFieldsEdit().add(saleDetailItemId);
        getFieldsEdit().add(saleDetailSizeId);
        getFieldsEdit().add(saleDetailQuantity);
        getFieldsEdit().add(saleDetailPrice);
        getFieldsEdit().add(saleDetailDiscountPercent);
        getFieldsEdit().add(saleDetailDiscountNominal);

        getFieldsList().clear();
        getFieldsList().add(saleDetailItemId);
        getFieldsList().add(saleDetailSizeId);
        getFieldsList().add(saleDetailQuantity);
        getFieldsList().add(saleDetailPrice);
        getFieldsList().add(saleDetailDiscountPercent);
        getFieldsList().add(saleDetailDiscountNominal);
        getFieldsList().add(saleDetailTotal);

        setController(new SaleDetailController(this));
    }

    @Override
    public StringBuffer process() {
        if (getAction().equals(Action.TRANS_DETAIL_ADD)) {
            return AddSize.process(this);
        }
        if (getAction().equals(Action.TRANS_DETAIL_LIST)) {
            Template template = new Template();
            template.loadTemplate("/com/buanalintas/sandals/pos/saledetail/trans-list.html");
            return PageTransactionDetailList.process(this, template);
        }
        return super.process();
    }

    @Override
    public String validate(Object data) {
        EntityManager em = getEntityManager();
        PosMasterStatus statusGood = Status.getStatusGood(em);
        PosTransactionSaleDetail saleDetail = (PosTransactionSaleDetail) data;
        PosMasterItemStock stock = Item.getStock(em, saleDetail.getSaleDetailItemId(), getCurrentUnit(), statusGood, saleDetail.getSaleDetailItemId().getItemColorId(), saleDetail.getSaleDetailSizeId());
        if (saleDetail.getSaleDetailQuantity().compareTo(stock.getItemStockValue()) > 0) {
            return saleDetail.getSaleDetailItemId() + " " + Dictionary.getValue(this, "insufficient stock") + ", " + Dictionary.getValue(this, "current stock: ") + ": " + stock.getItemStockValue() + " " + Dictionary.getValue(this, "will be sale") + ": " + saleDetail.getSaleDetailQuantity();
        }
        return null;
    }

    @Override
    public String doAction() {
        String barcode = Utility.getPostParameterEmpty(this, "barcode");
        int i = 0;
        if (!"".equals(barcode)) {
            HttpSession session = getRequest().getSession();
            try {
                System.out.println(" loop");
                EntityManager em = getEntityManager();
                PosMasterItem item = (PosMasterItem) em.createQuery("SELECT t FROM PosMasterItem t WHERE t.itemBarcode='" + barcode + "'").setHint(Persistence.REFRESH_HINT, true).getSingleResult();
                List<PosTransactionSaleDetail> list = ((List) session.getAttribute("transactions"));

                boolean exists = false;

                System.out.println("========>>>1");

                if (ada) {
                    for (PosTransactionSaleDetail sd : list) {
                        if (sd.getSaleDetailItemId().equals(item)) {
                            exists = true;
                            sd.setSaleDetailQuantity(sd.getSaleDetailQuantity() + 1);
                            sd.setSaleDetailTotal(sd.getSaleDetailTotal().add(sd.getSaleDetailPrice()));

                            ada = false;
                            break;

                        } else {
                            ada = true;
                            exists = false;
                        }
                    }
                }

                System.out.println("========>>>2");
                if (!exists) {
                    if (ada) {
                        PosTransactionSaleDetail detail = new PosTransactionSaleDetail();
                        System.out.println(item.getItemModel() + " kok jalan "
                                + detail.getSaleDetailQuantity());
                        detail.setSaleDetailItemId(item);
                            detail.setSaleDetailQuantity(1);

                        detail.setSaleDetailPrice(item.getItemPriceBasic());

                        detail.setSaleDetailDiscountNominal(BigDecimal.ZERO);
                        detail.setSaleDetailDiscountPercent(BigDecimal.ZERO);

                        detail.setSaleDetailTotal(item.getItemPriceBasic());
                        list.add(detail);
                    }
                    ada = true;
                    exists = false;
                }

            } catch (Exception e) {
                Logger.getInstance().log(e);
            }
        }
        return super.doAction();
    }
    
    class SaleDetailController extends Controller {

        public SaleDetailController(Page page) {
            super(page);
        }

        @Override
        public void beforeInsertDetail(Object data) {
            EntityManager em = getEntityManager();
            PosMasterStatus statusGood = Status.getStatusGood(em);
            System.out.println(statusGood.getStatusName());
            PosTransactionSaleDetail saleDetail = (PosTransactionSaleDetail) data;
//            PosMasterItemStock stock = Item.getStock(em, saleDetail.getSaleDetailItemId(), getCurrentUnit(), statusGood, s);
            BigDecimal total = BigDecimal.ZERO;
            BigDecimal quantity = new BigDecimal(saleDetail.getSaleDetailQuantity());
            total = saleDetail.getSaleDetailPrice().multiply(quantity);
            BigDecimal percent = BigDecimal.ZERO;
            try {
                percent = total.multiply(saleDetail.getSaleDetailDiscountPercent().divide(new BigDecimal(100)));
            } catch (Exception e) {
                Logger.getInstance().log(e);
            }
            total = total.subtract(percent);
            try {
                total = total.subtract(saleDetail.getSaleDetailDiscountNominal());
            } catch (Exception e) {
                Logger.getInstance().log(e);
            }
            saleDetail.setSaleDetailTotal(total);
        }
    }
}
